import xadmin
from .models import Device,DeviceStatus
from django.template.defaulttags import mark_safe
from django.conf import settings
from xadmin import views

class DeviceAdmin(object):
    # list_display=('name','desc','barcode')
    list_display=('name','desc','show_image')

    def barcode(self,object):
        import qrcode,os
        from users.models import SiteProfile
        qr = qrcode.QRCode(
            # version=1,
            # error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=6,
            border=1,
        )
        site =SiteProfile.objects.get(pk=1)
        image_path= os.path.join(settings.MEDIA_ROOT,"device")
        url = "http://"+site.site.domain+":"+str(site.port)+"/dev/"+str(object.id)
        qr.add_data(url)
        # img=qr.make(fit=True)

        img = qr.make_image()
        with open(os.path.join(image_path,str(object.id)+".jpg"), 'wb') as f:
            img.save(f)
        img_url= "/media/device/"+str(object.id)+".jpg"
        # return mark_safe(
        #                  "<img src='"
        #                  +img_url
        #                  +" '/>"
        #                  +"<br><b>设备名称"
        #                  +object.name
        #                  +"</b>"
        #                 )
        url_str = """
        <div col-md-2>
            <label class='label label-info'>{0}-{1}</label>
            
            <img src='{2}'/>
            </div>
        """.format(object.name,object.desc,img_url)
        return mark_safe(url_str)
    barcode.short_description="二维码"

    def show_image(self,obj):
        return mark_safe("<img src='{}'/>".format(obj.image))

    show_image.short_description ="二维码"


xadmin.site.register(Device,DeviceAdmin)


class BaseSetting(object):
    enable_themes = True
    use_bootswatch = True


xadmin.site.register(views.BaseAdminView, BaseSetting)


class DeviceStatusAdmin(object):
    list_display=['name','is_normal']
xadmin.site.register(DeviceStatus,DeviceStatusAdmin)



from .views import BarcodeView

xadmin.site.register_view(r'^barcode/$',BarcodeView,name="Barcode")